package com.njwb.day09.Work;

import org.apache.log4j.Logger;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;

public class LoginDemo {
    public static Logger logger = Logger.getLogger("src/com/njwb/day09/Work");
    private static List<User> userList = new ArrayList<>();
    private static  User[] user=new User[0];


    public static void main(String[] args) {
        loadUsers("src/com/njwb/day09/Work/user.txt");

        Scanner sc = new Scanner(System.in);
        System.out.print("请输入用户名：");
        String username = sc.nextLine();
        System.out.print("请输入密码：");
        String password = sc.nextLine();

        try {
            User user = login(username, password);
            System.out.println("登录成功！");
            System.out.println("欢迎您，" + user.getUsername() + "，您的角色是：" + user.getRole());
            System.out.println("权限描述：" + user.getRole().getDescription());
            user.getRole().work();
        } catch (UsernameNotFoundException e) {
            System.out.println("登录失败：" + e.getMessage());
            logger.error("用户名不存在");
        } catch (PasswordErrorException e) {
            System.out.println("登录失败：" + e.getMessage());
            logger.error("密码错误");
        }

    }

    // 加载用户信息
    private static void loadUsers(String filePath) {
        try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
            String line;
            while ((line = br.readLine()) != null) {
                String[] arr = line.split(":");
                if (arr.length == 3) {
                    user= Arrays.copyOf(user,user.length+1);
                    String username = arr[0];
                    String password = arr[1];
                    Role role = Role.valueOf(arr[2]); // 枚举匹配
                    userList.add(new User(username, password, role));
                    user[user.length-1]=new User(username, password, role);

                }
            }
        } catch (IOException e) {
            System.out.println("用户文件读取失败：" + e.getMessage());
        }
    }

    // 登录方法
    private static User login(String username, String password)
            throws UsernameNotFoundException, PasswordErrorException {
        for (User user : user) {
            if (user.getUsername().equals(username)) {
                if (user.getPassword().equals(password)) {
                    return user;
                } else {
                    throw new PasswordErrorException("密码错误！");
                }
            }
        }
        throw new UsernameNotFoundException("用户名不存在！");
    }
}
